package com.woniuxy01;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author 作者
 * @create 2025-08-11 14:37
 */
public class Test02 {

    public static void main(String[] args) throws InstantiationException, IllegalAccessException {

        Map<String,Object> map=new HashMap();
        map.put("sid",1);
        map.put("sname","zs");
        map.put("age",11);
        map.put("password","zs");
        map.put("email","emailxxx");
        map.put("phonexxx","phone");
        map.put("tid",1);
        map.put("bid",1);
//        map.put("x","xxx");
        Student student = mapToBean(map, Student.class);
        //new Student(); 给sid，sname,age赋值
        System.out.println(student);

        Book book = mapToBean(map, Book.class);
        System.out.println(book);
    }

    //通用的map转对象：1、创建对象，2.将对应的map中key的值，赋值给对象的对应属性
    public static <T>  T mapToBean(Map<String, Object> map,Class<T> clazz) throws InstantiationException, IllegalAccessException {
        //反射创建对象
        T t = clazz.newInstance();
        //获取对象的所有字段，和map中的key进行比较，给属性赋值
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            if (map.containsKey(field.getName())) {
                field.setAccessible(true);
                field.set(t,map.get(field.getName()));
            }
        }
        return t;
    }
}
